﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Collections;
using System.Data;
namespace FTchina.SMSServer
{
    /// <summary>
    ///SMSServer 的摘要说明
    /// </summary>
    public class SMSServer
    {

        private static object Oplock = new object();//锁
        private static object Oplaqulock = new object();//送入sms_sending锁
        public SMSServer()
        {
            //
            //TODO: 在此处添加构造函数逻辑
            //
        }

        /// <summary>
        /// 每条短信的价格
        /// </summary>
        public static double Price
        {
            get { return 0.10; }

        }

        /// <summary>
        /// 接收人同一批次最大数量，超过必须审核
        /// </summary>
        public static int CountLimit
        {
            get { return 50; }
        }






        #region 平台账号 获取用户名 获取充值来源  充值
        public enum Direction : int
        {
            UninPay = 1,//银联卡
            Alipay = 2,//支付宝
            ModByMan = 3,//手动修改
            Cost = 4,//发短信成功扣费
            CostReturn = 5,//发短信失败返还
            Cash = 6//现金
        }
        /// <summary>
        /// 通过SenderId获取SenderName
        /// </summary>
        /// <param name="SenderID"></param>
        /// <returns></returns>
        public static String GetSenderNameByID(string SenderID)
        {
            string SenderName = string.Empty;
            if (SenderID.Length > 0)
            {
                if (FTchina.Caching.FTchinaCache.IsExits("GetSenderNameByID" + SenderID))
                {
                    SenderName = FTchina.Caching.FTchinaCache.GetCache("GetSenderNameByID" + SenderID);//从缓存中获取
                }
                else
                {
                    string sql = "select sendername from senderlist where senderid='" + SenderID + "'";
                    SenderName = shujuku.GetDataTable(sql).Rows[0][0].ToString();
                    FTchina.Caching.FTchinaCache.AddCache("GetSenderNameByID" + SenderID, SenderName);//添加到缓存
                }
            }
            else
            {
                SenderName = "";
            }

            return SenderName;
        }


        /// <summary>
        /// 获取操作代码
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public static String GetDirectionNameByCode(string code)
        {
            string tmp = string.Empty;
            switch (code)
            {
                case "UninPay":
                    {
                        tmp = "银行卡充值";
                        break;
                    }
                case "ModByMan":
                    {
                        tmp = "后台手工修改";
                        break;
                    }
                case "CostReturn":
                    {
                        tmp = "短信失败返还";
                        break;
                    }
                case "Cost":
                    {
                        tmp = "短信成功扣费";
                        break;
                    }
                case "Alipay":
                    {
                        tmp = "支付宝充值";
                        break;
                    }
                case "Cash":
                    {
                        tmp = "现金";
                        break;
                    }

                default:
                    {
                        break;
                    }

            }
            return tmp;

        }


        /// <summary>
        /// 账户充值
        /// </summary>
        /// <param name="senderid">用户ID</param>
        /// <param name="money">金额</param>
        /// <returns></returns>
        public static Boolean SenderMoneyCharge(string senderid, decimal money)
        {
            string updateSenderMoneySql = "update SenderMoney set money=money+" + money + " where senderid='" + senderid + "'";
            if (shujukuRobot.ExecuteSql(updateSenderMoneySql))
            {
                LogNet.LogBLL.info(Library.MasterHelper.MasterName + "为用户" + senderid + SMSServer.GetSenderNameByID(senderid) + "充值" + money + "注入SenderMoney成功");
                return true;
            }
            else
            {
                LogNet.LogBLL.info(Library.MasterHelper.MasterName + "为用户" + senderid + SMSServer.GetSenderNameByID(senderid) + "充值" + money + "注入SenderMoney失败");
                return true;

            }

        }

        #endregion







        #region 模拟接口送来的短信

        /// <summary>
        /// 模拟接口送过来的短信
        /// </summary>
        public static void InsertSmsLog()
        {
            ArrayList al = new ArrayList();
            string[] senderid = { "32a8eb82ea964b5caf33d5eec7842369", "27405d01e99b4b08b49702c2b19a3dbf", "047a11ddf8844f2fa2b9ecb14f93f74b", "b80b1a1cfc8f4cb48d695c902476c8e4", "9f6ebbfc68ee46378744f9b7a1f5f16a", "3e82430a58b94351b26473910e7671c9" };

            string sql = @"INSERT INTO [Sms_Log]
           ([sendtime]
           ,[senderID]
           ,[target]
           ,[scontent]
           ,[state]
           ,[statetime]
           ,[smsguid]
           ,[taskstate]
           ,[shenhe]
           ,[sendcount])
     VALUES
           ('{0}'
           ,'{1}'
           ,'{2}'
           ,'{3}'
           ,'{4}'
           ,'{5}'
           ,'{6}'
           ,'{7}'
           ,'{8}'
            ,'0')";
            string sqlx = string.Empty;
            for (int i = 0; i < 10000; i++)
            {
                int x = new Random().Next(0, 6);

                sqlx = string.Format(sql,
                    DateTime.Now.ToString(),
                    senderid[x].ToString(),
                   GetRadomPhone(),
                    basic.GetGuid(basic.RandEnum.Chinese, 70),
                    "2",
                    DateTime.Now.ToString(),
                    basic.GetGuid(),
                    "2",
                    "2"
                    );
                //  LogNet.LogBLL.info(sqlx);
                al.Add(sqlx);
            }

            shujukuRobot.ExecuteSqlTransaction(al);

        }



        /// <summary>
        /// 获取一个伪造的电话号码
        /// </summary>
        /// <returns></returns>
        public static string GetRadomPhone()
        {
            string[] tou = { "156", "186", "131", "135", "189", "187", "155", "132" };
            Random rd = new Random(Guid.NewGuid().GetHashCode());
            int i = rd.Next(0, 7);
            string ptou = tou[i];

            Random rdx = new Random(Guid.NewGuid().GetHashCode());
            string phonenumber = rdx.Next(10000000, 99999999).ToString();
            return ptou + phonenumber;
        }


        #endregion



        #region 接收客户的短信
        /// <summary>
        /// 处理入口
        /// </summary>
        /// <param name="Senderid"></param>
        /// <param name="Target"></param>
        /// <param name="Content"></param>
        public static string ReceivemainDo(string Senderid, string Target, string Content)
        {
            /***
             *1、先检查用户是否合法
             *2、检查短信，大于70字的拆分成2条， 
             *3、根据短信的条数，检查平台余额， 
             *4 、送入sms_log,扣除用户余额,检查敏感字符，带有敏感字符的直接禁止，等待审核
             *5、判断发送人数，大于设定的数值置为禁止，否则放行
             * 
             * 
             * 
             ***/

            string ReturnWords = string.Empty;
           
            if (DateTime.Now.Hour >= 8 && DateTime.Now.Hour < 21)
            {

                //初始化敏感词过滤器
                FTchina.SMSServer.BadWordsFilter bf = new FTchina.SMSServer.BadWordsFilter();

                if (CheckSenderID(Senderid))
                {//检查用户是否合法

                    decimal Smoney = 0;
                    int SmsCount = 0;//短信拆分后的条数
                    ArrayList al = FormatSms(Senderid, Target, Content, bf, out SmsCount);
                    if (CheckSenderMoney(Senderid, al.Count, out Smoney))
                    {//检查通过
                        if (shujuku.ExecuteSqlTransaction(al))
                        {//插入sms_log成功，然后扣费
                            if (ReduceSenderMoenyBycount(Senderid, SmsCount))
                            {
                                InsertSucessMoneyLog(Senderid, SmsCount);

                                LogNet.LogBLL.info("接收" + Senderid + FTchina.SMSServer.SMSServer.GetSenderNameByID(Senderid) + "短信" + SmsCount + "条扣费成功");
                                ReturnWords = "短信发送成功，请不要重复提交。";



                                //LogNet.LogBLL.info("注入发送队列自动触发" + Senderid + FTchina.SMSServer.SMSServer.GetSenderNameByID(Senderid) + "短信" + al.Count + "条");
                                //SendToTask(Senderid);
                                //LogNet.LogBLL.info("触发自动注入结束");

                            }
                        }
                        else
                        {
                            LogNet.LogBLL.info(Senderid + FTchina.SMSServer.SMSServer.GetSenderNameByID(Senderid) + "短信" + SmsCount + "条注入Sms_Log失败，所有短信抛弃");
                            ReturnWords = "提交失败，请稍候再试";
                        }
                    }
                    else
                    {
                        LogNet.LogBLL.info(Senderid + FTchina.SMSServer.SMSServer.GetSenderNameByID(Senderid) + "切割后短信" + SmsCount + "条,平台余额" + Smoney + ",不足，所有短信抛弃");
                        ReturnWords = "短信" + SmsCount + "条,平台余额" + Smoney + ",不足";
                    }


                }
                else
                {
                    LogNet.LogBLL.info(Senderid + "不合法，所有短信抛弃");
                    ReturnWords = "账户不合法请先注册";

                }
            }
            else
            {
                LogNet.LogBLL.info(Senderid + "超出正常营业时间，所有短信抛弃");
                ReturnWords = "失败，请在8至21点内发送短信";
            }
            return ReturnWords;

        }
        /// <summary>
        /// 检查用户是否存在
        /// </summary>
        /// <param name="Senderid"></param>
        /// <returns></returns>
        private static Boolean CheckSenderID(string Senderid)
        {
            bool flag = true;
            string sql = "select top 1 * from senderList where senderid='" + Senderid + "'";
            if (shujuku.testread(sql))
            {
                using (DataTable dt = shujuku.GetDataTable(sql))
                {
                    if (dt.Rows[0]["state"].ToString() != "0")
                    {//状态不正常
                        flag = false;
                    }
                }
            }
            else
            {//无此用户
                flag = false;
            }
            // LogNet.LogBLL.info(sql);
            return flag;
        }

        /// <summary>
        /// 检查用户余额是否能够支付本次的费用
        /// </summary>
        /// <param name="Senderid"></param>
        /// <returns></returns>
        private static Boolean CheckSenderMoney(string Senderid, int count, out decimal Smoney)
        {
            string sql = "select top 1 money from SenderMoney where senderid='" + Senderid + "'";
            decimal money = Convert.ToDecimal(FTchina.shujuku.GetDataTable(sql).Rows[0][0]);
            decimal Cost = Convert.ToDecimal(FTchina.SMSServer.SMSServer.Price * count);
            Smoney = money;
            return money >= Cost;
        }

        /// <summary>
        /// 对应的账号扣除短信钱
        /// </summary>
        /// <param name="senderid"></param>
        /// <param name="count"></param>
        /// <returns></returns>
        public static Boolean ReduceSenderMoenyBycount(string senderid, int count)
        {
            decimal pri = Convert.ToDecimal(FTchina.SMSServer.SMSServer.Price * count);
            string sql = @"UPDATE    SenderMoney
                        SET   money = money - {0}
                        WHERE  senderid='{1}'  ";
            return shujukuRobot.ExecuteSql(string.Format(sql, pri, senderid));
        }

        /// <summary>
        /// 插入一条批量短信成功扣费日志
        /// </summary>
        /// <param name="senderid"></param>
        /// <param name="smsguid"></param>
        /// <returns></returns>
        private static Boolean InsertSucessMoneyLog(string senderid, int count)
        {
            FTchina.Models.SenderMoney_Log mSenderMoney_Log = new FTchina.Models.SenderMoney_Log();
            mSenderMoney_Log.Id = 0;
            mSenderMoney_Log.SenderID = senderid;
            mSenderMoney_Log.Money = Convert.ToDecimal(-SMSServer.Price * count);
            mSenderMoney_Log.Date = DateTime.Now;
            mSenderMoney_Log.Memo = "平台接收" + count + "条短信";
            mSenderMoney_Log.Direction = "Cost";
            mSenderMoney_Log.Smsguid = string.Empty;
            mSenderMoney_Log.Oper = "短信平台";
            bool flag = FTchina.BLL.SenderMoney_LogManager.AddSenderMoney_Log(mSenderMoney_Log) > 0;
            return flag;
        }

        /// <summary>
        /// 将短信按70字拆开计费，并进行过滤，压送时不拆分
        /// </summary>
        /// <param name="Senderid"></param>
        /// <param name="Target"></param>
        /// <param name="Content"></param>
        /// <returns></returns>
        private static ArrayList FormatSms(string Senderid, string Target, string Content, BadWordsFilter bf, out int SmsCount)
        {
            int _SmsCount = 0;
            string Insertsql = @"INSERT INTO [Sms_Log]
           ([sendtime]
           ,[senderID]
           ,[target]
           ,[scontent]
           ,[state]
           ,[statetime]
           ,[smsguid]
           ,[taskstate]
           ,[shenhe]
           ,[sendcount])
     VALUES
           ('{0}'
           ,'{1}'
           ,'{2}'
           ,'{3}'
           ,'{4}'
           ,'{5}'
           ,'{6}'
           ,'{7}'
           ,'{8}'
            ,'0')";

            ArrayList al = new ArrayList();//存放短信
            string[] Targets = Target.Split(',');


            string shenhe = (bf.HasBadWord(Content)) ? "0" : "2";//检查敏感字符串0禁止2自动放行
            if (shenhe == "2")
            {//先检查敏感字符，然后看条数
                shenhe = (Targets.Length >= SMSServer.CountLimit) ? "0" : "2";//0禁止2自动放行
            }

            string sqlx = string.Empty;
            foreach (string TragetSingle in Targets)
            {
                if (TragetSingle.Trim().Length == 0) continue;
                List<String> ms = new FTchina.SMSServer.SMSSplite().StringSplit(Content);
                _SmsCount += ms.Count;//拆分后的短信条数加一


                #region 发送不拆分
                ////foreach (String m in ms)
                ////{
                
                //sqlx = string.Format(Insertsql,
                //          DateTime.Now.ToString(),
                //         Senderid,
                //        TragetSingle.Trim(),
                //         Content,
                //          "2",
                //          DateTime.Now.ToString(),
                //          basic.GetGuid(),
                //          "2",
                //          shenhe
                //          );
                //al.Add(sqlx);
                ////}
                #endregion
                #region 发送拆分
                for (int i = ms.Count-1; i >= 0; i--)
                {//倒叙插入，保证先发第一条
                    sqlx = string.Format(Insertsql,
                                  DateTime.Now.ToString(),
                                 Senderid,
                                TragetSingle.Trim(),
                                 ms[i],
                                  "2",
                                  DateTime.Now.ToString(),
                                  basic.GetGuid(),
                                  "2",
                                  shenhe
                                  );
                        al.Add(sqlx);
                     
                }
                #endregion
            }
            SmsCount = _SmsCount;
            return al;
        }
        #endregion


        #region 抓取发送队列

        /// <summary>
        /// 根据用户编码将待发送短信压入发送队列
        /// </summary>
        /// <param name="senderid"></param>
        public static void SendToTask(string senderid, string lockguid)
        {
            DataTable dt = GetShenHePassSmsguidBySenderId(senderid);
            foreach (DataRow dr in dt.Rows)
            {
                if (CheckSendCount(dr["smsguid"].ToString())) continue;//已经发送过的跳过 

                SendingBySmsguid(dr["smsguid"].ToString(), lockguid);
            }
        }
        /// <summary>
        /// 提取指定数量的待发送短信压入发送队列
        /// </summary>
        /// <param name="num"></param>
        public static void SendToTask(int num, string lockguid)
        {
            lock (Oplaqulock)
            {
                using (DataTable dt = GetShenHePassSmsguidByNum(num, lockguid))
                {
                    foreach (DataRow dr in dt.Rows)
                    {
                        if (CheckSendCount(dr["smsguid"].ToString())) continue;//已经发送过的跳过 

                        SendingBySmsguid(dr["smsguid"].ToString(), lockguid);
                    }
                }
            }
        }


        /// <summary>
        /// 用事务将待发短信压入发送通道
        /// </summary>
        /// <param name="num"></param>
        /// <param name="lockguid"></param>
        /// <returns></returns>
        public static Boolean SendToTaskTransaction(int num, string lockguid)
        {
            //审核不能是禁止，发送不能是成功，抓取不能是成功的
            string Filter = " shenhe<>0 and state<>'1' and  taskstate <> 1 and (lockguid ='" + lockguid + "')";
            string order = "  order by id asc ";//先进先出
            string sql = "select top " + num + " smsguid from sms_log where " + Filter + order;


            string locksql = "update sms_log set lockguid='" + lockguid + "' where id in (select  top " + num + " id from sms_log where  shenhe<>0 and state<>'1' and  taskstate <> 1 and (lockguid is null or lockguid ='') " + order + ")";

            string sqlget = "Insert into Sms_sending(senderid, smsguid, target,scontent) select senderid, smsguid, target,scontent from Sms_Log where lockguid='" + lockguid + "' order by id asc";
            //置返回状态
            string sqlreset = " update Sms_Log set taskstate=1 where lockguid='" + lockguid + "'";

            ArrayList al = new ArrayList();
            al.Add(locksql);//先上锁
            al.Add(sqlget);//插入sms_sending
            al.Add(sqlreset);//将短信置为已拉取
            return shujukuRobot.ExecuteSqlTransaction(al);


        }



        /// <summary>
        /// 获取某人的待发送短信
        /// </summary>
        /// <param name="senderid"></param>
        /// <returns></returns>
        private static DataTable GetShenHePassSmsguidBySenderId(string senderid)
        {
            //审核不能是禁止，发送不能是成功，拉取不能是成功
            string Filter = " shenhe<>0 and state<>'1' and taskstate<>1  and senderid='" + senderid + "' ";
            string order = "  order by id asc ";//先进先出
            string sql = "select  smsguid from sms_log where " + Filter + order;
            return shujukuRobot.GetDataTable(sql);
        }
        /// <summary>
        /// 获取一定量的待发送短信
        /// </summary>
        /// <param name="num"></param>
        /// <returns></returns>
        private static DataTable GetShenHePassSmsguidByNum(int num, string lockguid)
        {


            //审核不能是禁止，发送不能是成功，抓取不能是成功的
            string Filter = " shenhe<>0 and state<>'1' and  taskstate <> 1 and (lockguid ='" + lockguid + "')";
            string order = "  order by id asc ";//先进先出
            string sql = "select top " + num + " smsguid from sms_log where " + Filter + order;


            string locksql = "update sms_log set lockguid='" + lockguid + "' where id in (select  top " + num + " id from sms_log where  shenhe<>0 and state<>'1' and  taskstate <> 1 and (lockguid is null or lockguid ='') " + order + ")";
            shujukuRobot.ExecuteSql(locksql);


            // basic.Log("获取一定量的待发送短信" + locksql + "------" + sql);


            return shujukuRobot.GetDataTable(sql);
        }
        /// <summary>
        /// 根据Smsguid将短信压入发送队列
        /// </summary>
        /// <param name="smsguid"></param>
        /// <returns></returns>
        private static Boolean SendingBySmsguid(string smsguid, string lockguid)
        {

            bool flag;
            if (ChekMoneyBeforSending(smsguid))
            {//先检查账户余额

                if (CheckSendCount(smsguid))
                {//检查是否已经发送过了 多线程下的问题
                    flag = false;
                    LogNet.LogBLL.info("短信" + smsguid + "压入队列失败，原因已经发送过了");
                }
                else
                {
                    //从sms_log送入发送队列
                    string sqlget = "Insert into Sms_sending(senderid, smsguid, target,scontent) select senderid, smsguid, target,scontent from Sms_Log where smsguid='" + smsguid + "' order by id asc";
                    //置返回状态
                    string sqlreset = " update Sms_Log set taskstate={0} where smsguid='{1}'";
                    int result = shujukuRobot.ExecuteCommand(sqlget);
                    flag = result > 0;
                    if (flag)
                    {
                        //将taskstate置为1，表示拉取成功，送入发送队列
                        shujukuRobot.ExecuteSql(string.Format(sqlreset, 1, smsguid));
                        //扣除相应的钱，这个操作限制放在短信平台的接收上，接收即扣钱。
                        //CostBySmsguid(smsguid, result);
                    }
                    else
                    {
                        //将taskstate置为0，表示拉取失败
                        shujukuRobot.ExecuteSql(string.Format(sqlreset, 0, smsguid));
                    }
                }
            }
            else
            {
                flag = false;
                LogNet.LogBLL.info("短信" + smsguid + "压入队列失败，原因账户余额不足");
            }
            return flag;
        }

        //压入成功后扣除相应的费用
        private static Boolean CostBySmsguid(string smsguid, int count)
        {
            decimal pri = Convert.ToDecimal(Price * count);
            string sql = @"UPDATE    SenderMoney
                        SET   money = money - {0}
                        WHERE     (senderID IN
                          (SELECT  TOP 1    senderID
                            FROM          Sms_Log AS sl
                            WHERE      (smsguid = '{1}')))";
            return shujukuRobot.ExecuteSql(string.Format(sql, pri, smsguid));
        }


        /// <summary>
        /// 压入队列前要先检查账户余额，账户不足的话就不能发送了
        /// </summary>
        /// <param name="smsguid"></param>
        /// <returns></returns>
        private static Boolean ChekMoneyBeforSending(string smsguid)
        {
            ///用户应付钱数
            int count = Convert.ToInt32(shujukuRobot.GetDataTable("select count(id)  from sms_log where smsguid='" + smsguid + "'").Rows[0][0]);
            decimal pri = Convert.ToDecimal(Price * count);

            string sql = @"select money from   SenderMoney
                        WHERE     (senderID IN
                          (SELECT   TOP 1   senderID
                            FROM          Sms_Log AS sl
                            WHERE      (smsguid = '{0}')))";
            //用户现有余额
            decimal money = Convert.ToDecimal(shujukuRobot.GetDataTable(string.Format(sql, smsguid)).Rows[0][0]);
            return money >= pri;
        }

        #endregion


        #region 发送短信

        /// <summary>
        /// 发送短信给用户
        /// </summary>
        public static void Send2target(int num, string lockguid)
        {
            lock (Oplock)
            {
                //string GetSendingSql = "select top " + num + " * from sms_sending order by id asc";
                string GetSendingSql = "SELECT TOP (" + num + ")  * FROM  Sms_sending   WHERE  lockguid ='" + lockguid + "' ";

                //先添加lock标识位
                string locksql = "update sms_sending set lockguid='" + lockguid + "' where id in (select top  (" + num + ")  id from  Sms_sending  WHERE  lockguid is null or  lockguid='' )";
                shujukuRobot.ExecuteSql(locksql);

                //basic.Log(locksql + ";" + GetSendingSql);


                DataTable dt = shujukuRobot.GetDataTable(GetSendingSql);
                foreach (DataRow dr in dt.Rows)
                {
                    //basic.Log(dr["id"]);
                    if (CheckSendCount(dr["smsguid"].ToString())) continue;//已经发送过的跳过 
                    if (SendSms(dr["smsguid"].ToString(),
                        dr["senderid"].ToString(),
                        dr["target"].ToString(),
                        dr["scontent"].ToString()
                        ))
                    {//发送成功

                        //将短信置为已发送
                        SendSucess(dr["smsguid"].ToString(), dr["senderid"].ToString());

                        //插入一条短信扣费日志 
                        //接收到用户短信的时候已经扣费了，所以不要再次扣费了。
                        // InsertSucessMoneyLog(dr["smsguid"].ToString(), dr["senderid"].ToString());
                        SendCountPlus1(dr["senderid"].ToString());
                    }
                    //else
                    //{//发送失败

                    //    //将短信置为发送失败
                    //    SendFailure(dr["smsguid"].ToString(), dr["senderid"].ToString());

                    //    //插入一条发送失败返费日志
                    //    //发送失败不能将钱返回去，因为再次重发失败会再次返钱。 如果返费了，那么这条短信应该就再也不发了
                    //    // InsertFailureMoneyLog(dr["smsguid"].ToString(), dr["senderid"].ToString());
                    //    // SenderMoneyAdd(dr["senderid"].ToString());
                    //}

                }

            }
        }

        /// <summary>
        /// 发送短信
        /// </summary>
        /// <param name="smsguid"></param>
        /// <param name="senderid"></param>
        /// <param name="target"></param>
        /// <param name="content"></param>
        /// <returns></returns>
        private static Boolean SendSms(string smsguid, string senderid, string target, string content)
        {
            // 压入猫池的时候的时候先删除，避免多次发送
            //将短信从通道删除
            DeleteSmsFromSending(smsguid, senderid);

            if (InsertSended(smsguid))
            {
                return FTchina.SMSServer.SmsChannel.Sned2Channel(target, content, smsguid);
            }

            else
            {
                LogNet.LogBLL.error("插入SMS_Sended错误" + smsguid);
                return false;
            }
        }

        /// <summary>
        /// 将短信放到已发送接口的记录
        /// </summary>
        /// <param name="smsguid"></param>
        /// <returns></returns>
        private static Boolean InsertSended(string smsguid)
        {
            string sql = "insert into Sms_Sended (smsguid) values ('{0}')";
            return shujuku.ExecuteCommand(string.Format(sql, smsguid)) > 0;
        }

        /// <summary>
        /// 检查是否已经发送过
        /// </summary>
        /// <param name="smsguid"></param>
        /// <returns>True 已经发送过，Fasle 尚未发送</returns>
        private static Boolean CheckSendCount(string smsguid)
        {
            string sql = "select top 1 sendcount from sms_log where smsguid='" + smsguid + "'";
            string s = "0";
            try
            {
                s = shujuku.GetDataTable(sql, smsguid).Rows[0][0].ToString();

            }
            catch (Exception e)
            {
                s = "999";//返回以及发送过
            }
            return Convert.ToInt32(s) > 1;
        }
        /// <summary>
        /// 处理发送失败的短信
        /// </summary>
        /// <param name="smsguid"></param>
        /// <param name="senderid"></param>
        /// <returns></returns>
        private static Boolean SendFailure(string smsguid, string senderid)
        {
            string sql = "update sms_log set state='0' ,statetime='" + DateTime.Now.ToString() + "' where smsguid='" + smsguid + "' and senderid='" + senderid + "'";
            LogNet.LogBLL.info(senderid + "----" + smsguid + "发送失败");
            return shujukuRobot.ExecuteSql(sql);
        }
        /// <summary>
        /// 处理发送成功的短信
        /// </summary>
        /// <param name="smsguid"></param>
        /// <param name="senderid"></param>
        /// <returns></returns>
        private static Boolean SendSucess(string smsguid, string senderid)
        {
            ///加入taskstate是为了跟抓取发送队列统一起来。
            string sql = "update sms_log set sendcount=sendcount+1, state='1' , statetime='" + DateTime.Now.ToString() + "',taskstate=1 where smsguid='" + smsguid + "' and senderid='" + senderid + "'";
            return shujukuRobot.ExecuteSql(sql);
        }
        /// <summary>
        /// 将短信从通道删除
        /// </summary>
        /// <param name="smsguid"></param>
        /// <param name="senderid"></param>
        /// <returns></returns>
        private static Boolean DeleteSmsFromSending(string smsguid, string senderid)
        {
            string sql = "delete from sms_sending where smsguid='" + smsguid + "' and senderid='" + senderid + "'";
            return shujukuRobot.ExecuteSql(sql);
        }
        /// <summary>
        /// 发送成功用户发送短信数目加一
        /// </summary>
        /// <param name="senderid"></param>
        /// <returns></returns>
        private static Boolean SendCountPlus1(string senderid)
        {
            string sql = "update  SenderMoney set sended=sended+1 where senderid='" + senderid + "'";
            return shujukuRobot.ExecuteSql(sql);
        }

        /// <summary>
        /// 用户帐户减少一条短信的钱
        /// </summary>
        /// <param name="senderid"></param>
        /// <returns></returns>
        private static Boolean SenderMoneyReduce(string senderid)
        {
            decimal pri = Convert.ToDecimal(SMSServer.Price * 1);
            string sql = "update  SenderMoney set money=money -" + pri + " where senderid='" + senderid + "'";
            return shujukuRobot.ExecuteSql(sql);
        }
        /// <summary>
        /// 用户帐户增加一条短信的钱
        /// </summary>
        /// <param name="senderid"></param>
        /// <returns></returns>
        private static Boolean SenderMoneyAdd(string senderid)
        {
            decimal pri = Convert.ToDecimal(SMSServer.Price * 1);
            string sql = "update  SenderMoney set money=money +" + pri + " where senderid='" + senderid + "'";
            return shujukuRobot.ExecuteSql(sql);
        }
        /// <summary>
        /// 插入一条短信成功扣费日志
        /// </summary>
        /// <param name="senderid"></param>
        /// <param name="smsguid"></param>
        /// <returns></returns>
        private static Boolean InsertSucessMoneyLog(string smsguid, string senderid)
        {
            FTchina.Models.SenderMoney_Log mSenderMoney_Log = new FTchina.Models.SenderMoney_Log();
            mSenderMoney_Log.Id = 0;
            mSenderMoney_Log.SenderID = senderid;
            mSenderMoney_Log.Money = Convert.ToDecimal(-SMSServer.Price * 1);
            mSenderMoney_Log.Date = DateTime.Now;
            mSenderMoney_Log.Memo = string.Empty;
            mSenderMoney_Log.Direction = "Cost";
            mSenderMoney_Log.Smsguid = smsguid;
            mSenderMoney_Log.Oper = "短信平台";
            bool flag = FTchina.BLL.SenderMoney_LogManager.AddSenderMoney_Log(mSenderMoney_Log) > 0;
            return flag;
        }
        /// <summary>
        /// 插入一条短信失败返费日志
        /// </summary>
        /// <param name="senderid"></param>
        /// <param name="smsguid"></param>
        /// <returns></returns>
        private static Boolean InsertFailureMoneyLog(string smsguid, string senderid)
        {
            FTchina.Models.SenderMoney_Log mSenderMoney_Log = new FTchina.Models.SenderMoney_Log();
            mSenderMoney_Log.Id = 0;
            mSenderMoney_Log.SenderID = senderid;
            mSenderMoney_Log.Money = Convert.ToDecimal(SMSServer.Price * 1);
            mSenderMoney_Log.Date = DateTime.Now;
            mSenderMoney_Log.Memo = string.Empty;
            mSenderMoney_Log.Direction = "CostReturn";
            mSenderMoney_Log.Smsguid = smsguid;
            mSenderMoney_Log.Oper = "短信平台";
            bool flag = FTchina.BLL.SenderMoney_LogManager.AddSenderMoney_Log(mSenderMoney_Log) > 0;
            return flag;
        }
        #endregion





        #region
        /// <summary>
        /// 通过用户ID获取账户余额
        /// </summary>
        /// <param name="Senderid"></param>
        /// <returns></returns>
        public static string GetSenderMoneyBySenderID(string Senderid)
        {
            string sql = "select top 1 money from SenderMoney where senderid='" + Senderid + "'";

            return FTchina.shujuku.GetDataTable(sql).Rows[0][0].ToString();
        }
        #endregion
    }
}